# -*- coding: UTF-8 -*-
import math
import os.path
import random
import ctypes
import ctypes.wintypes
import pyautogui
import win32api
import win32con
import win32gui
from airtest.core.api import *
import psutil

base_path = os.path.dirname(os.path.abspath(__file__))

# 启动游戏
def start_menghua(apps):
    '''
    :param apps: 只启动应用的列表
    :return:
    '''
    win32api.ShellExecute(0, 'open', r'C:\Users\Administrator\Desktop\Sandboxie-Plus.lnk', '', '', 1)
    time.sleep(10)
    n = len(apps)
    for i in range(n):
        # 1.启动程序（game)
        win32api.ShellExecute(0, 'open', f'C:\\Users\\Administrator\\Desktop\\mhxy\\[{apps[i]}]MyLauncher_x64r.lnk', '', '', 1)
        print(f"正在启动   {apps[i]}")
        sleep(10)
    # 启动DisplayFusion程序
    # DisplayFusion = r"C:\Users\Public\Desktop\DisplayFusion.lnk"
    # win32api.ShellExecute(0, 'open', DisplayFusion, '', '', 1)
# 登录游戏
def login(hwnd):
    try :
        connect_device(f"Windows:///{hwnd}")
        # 点击进入游戏
        pos = wait(Template(r"tpl1722166917534.png", record_pos=(0.039, 0.071), resolution=(969, 807)),20)
        sleep(5)
        app_touch(pos, [-5, 5], [-1, 1], times=1)
        # 点击登录游戏
        pos = wait(Template(r"tpl1722166949111.png", record_pos=(0.038, 0.153), resolution=(969, 807)),20)
        sleep(5)
        app_touch(pos, [-5, 5], [-1, 1], times=1)
    except :
        print("登录失败")
# 缩小窗口
def pich_swipe_app(pc_sreen,apps_count,locs,now_posit,app_orl_posit,app_orl_szie):
    '''
    :param pc_sreen: pc分辨率（1920,1080）
    :param apps_count: 游戏窗口个数
    :param locs: 一行需要排列几个窗口
    :param now_posit: 移动到为止（0,0），表示第1行，第1列
    :param app_orl_posit: 启动游戏的左上角的坐标（447,117）
    :param app_orl_szie: 启动后的游戏尺寸大小（1025,797）
    :return:
    '''

    '''
    缩小程序窗口，并移动到指定的位置
    '''
    connect_device(f'Windows:///')
    # 1.计算标题宽度
    title_k = app_orl_szie[1] * 0.0376 # （假设标题宽带占程序窗口的百分比为 2 )


    # 2.计算有多少行
    rows = math.ceil( apps_count / locs)
    print(f"一共{rows}行")
    # 计算比例
    app_rat = 1/locs
    try:
        cover_rat = 1/(rows-1) # 覆盖比例
    except:
        cover_rat = 1

    # 3.缩放程序窗口
    orl_right_x = int(app_orl_posit[0] + app_orl_szie[0]) # 原窗口最右边x值
    # 假设缩放的位置 y = 100 ,从顶点向下 + 100
    orl_right_y = int(app_orl_posit[1]+100)
    print(f"缩放窗口移动位置起点{(orl_right_x,orl_right_y)}")
    now_right_x = int(app_orl_posit[0]+pc_sreen[0]*app_rat)
    print(f"缩放窗口移动位置终点{(now_right_x,orl_right_y)}")
    swipe((orl_right_x,orl_right_y),(now_right_x,orl_right_y),duration=1, steps=6)
    sleep(3)

    # 4.计算缩小后标题中心点坐标
    orl_title_center_x = int(app_orl_posit[0] + (now_right_x - app_orl_posit[0]) / 2)
    orl_title_center_y = int(app_orl_posit[1] + title_k / 2)
    print(f"按住标题移动位置起点{(orl_title_center_x, orl_title_center_y)}")


    # 5.计算缩小后的窗口尺寸
    now_app_length = now_right_x - app_orl_posit[0]  # 缩小后的窗口长度
    now_app_wide = (now_app_length / app_orl_szie[0]) * app_orl_szie[1] +20 # 根据长度缩放比例，计算现在宽度 增加高度20间隔

    # 超过2行，就考虑重叠，按照重叠 1-app_rat 显示，也就说，只露出 程序宽度*app_rat
    # 移动到指定位置 now_posit
    if locs == 4:
        if now_posit[1] == (rows-1):
            now_title_center_x = int(now_app_length * (now_posit[0] + 0.5))
            now_title_center_y = int(pc_sreen[1]-now_app_wide-40 + title_k / 2) #整个屏幕 高度 - 底部(40) - 窗口高度 + 标题的一半
        else:
            now_title_center_x = int(now_app_length*(now_posit[0]+0.5))
            now_title_center_y = int(title_k/2 + now_app_wide*now_posit[1]) # 不考虑第一层和第二层的覆盖

        print(f"按住标题移动位置终点{(now_title_center_x, now_title_center_y)}")
        swipe((orl_title_center_x, orl_title_center_y), (now_title_center_x, now_title_center_y), duration=1, steps=6)
        sleep(3)

    else:
        now_title_center_x = int(now_app_length*(now_posit[0]+0.5))
        now_title_center_y = int(title_k/2 + now_app_wide*now_posit[1]*cover_rat)

        print(f"按住标题移动位置终点{(now_title_center_x, now_title_center_y)}")
        swipe((orl_title_center_x, orl_title_center_y), (now_title_center_x, now_title_center_y), duration=1, steps=6)
        sleep(3)
    # 标题的中心点坐标，缩小后长度
    return (now_title_center_x, now_title_center_y),now_app_length
# 最小化应用
def minimize_app(condit):
    # 根据句柄，最小化
    hwnd_list = []
    win32gui.EnumWindows(lambda hwnd, param: param.append(hwnd), hwnd_list)
    for hwnd in hwnd_list:
        title = win32gui.GetWindowText(hwnd)
        if condit == "pycham":
            if (title.find(".py")>= 0):
                print("句柄：", hwnd, "标题：", title)
                win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_MINIMIZE, 0)
                break
        if condit == "menghua":
            if (title.find("梦幻西游")>= 0):
                print("句柄：", hwnd, "标题：", title)
                win32gui.SendMessage(hwnd, win32con.WM_SYSCOMMAND, win32con.SC_MINIMIZE, 0)
                break
# 根据标题获取句柄
def get_all_windows(condit):
    hwnd_list = []
    # 获取所有子窗口
    hwnds = []
    win32gui.EnumWindows(lambda hwnd, param: param.append(hwnd), hwnd_list)
    for hwnd in hwnd_list:
        title = win32gui.GetWindowText(hwnd)
        if (title.find(condit)>= 0):
            print("句柄：", hwnd, "标题：", title)
            hwnds.append(hwnd)
    return hwnds
# 关闭游戏
def close_app():
    # 根据进程名称获取进程信息
    pids = []
    for proc in psutil.process_iter(['pid', 'name']):
        if proc.info['name'] == 'MyGame_x64r.exe':
            print(proc.info)
            pids.append(proc.info['pid'])
    for pid in pids:
        os.kill(pid, 9)
        sleep(2)
# 登录游戏，自动缩放
def start_pailie_login(apps,pc_sreen,locs,is_swipe):
    '''
    :param apps:
    :param pc_sreen:
    :param locs:
    :param is_swipe:
    :return:
    '''
    start_menghua(apps)
    hwnds = get_all_windows("梦幻西游")
    for i in range(len(hwnds)):
        sleep(5)
        login(hwnds[i])
    # 加载，并显示
    if is_swipe:
        apps_count = len(hwnds) #程序总数
        rows = math.ceil(apps_count / locs) #多少行
        now_posits = []

        for j in range(rows):
            for i in range(locs):
                if (j == rows - 1) and (i == apps_count % locs): # 用于判断坐标个数
                    break
                now_posits.append([i, j])

        for i in range(apps_count):
            connect_device(f'Windows:///{hwnds[i]}')
            now_posit = now_posits[i]
            print(f"坐标编号列表：{now_posit}")

            # 根据程序 窗口尺寸 得到坐标
            left,top,right,bottom = get_window_rect(hwnds[i])
            app_orl_posit = (left,top)
            app_orl_szie = (right - left,bottom - top)

            pich_swipe_app(pc_sreen,apps_count,locs,now_posit,app_orl_posit,app_orl_szie)
            sleep(3)


# 根据标题关键字 获取单个句柄值
def get_hwnd_from_title(keywords):
    # 获取所有子窗口
    hwnds = get_all_windows("梦幻西游")
    if keywords:
        hwnds_ = []
        for keyword in keywords:
            for hwnd in hwnds:
                title = win32gui.GetWindowText(hwnd)
                if (title.find(f"[{str(keyword)}]") >= 0):
                    print("句柄：", hwnd, "标题：", title)
                    hwnds_.append(hwnd)
                    break
        hwnds = hwnds_
    return hwnds

def get_window_rect(hwnd):
    '''
    根据句柄获取窗口位置
    :param hwnd: 句柄值
    :return:
    '''
    try:
        f = ctypes.windll.dwmapi.DwmGetWindowAttribute
    except WindowsError:
        f = None
    if f:
        rect = ctypes.wintypes.RECT()
        DWMWA_EXTENDED_FRAME_BOUNDS = 9
        f(ctypes.wintypes.HWND(hwnd),
          ctypes.wintypes.DWORD(DWMWA_EXTENDED_FRAME_BOUNDS),
          ctypes.byref(rect),
          ctypes.sizeof(rect)
          )
        # 左上和右下
        print('窗口左上角坐标：({}, {})'.format(rect.left, rect.top))
        print('窗口右下角坐标：({}, {})'.format(rect.right, rect.bottom))
        return rect.left, rect.top, rect.right, rect.bottom

def app_touch(pcos,x_ofset=[0,0],y_ofset=[0,0],times=1, **kwargs):
    '''
    重构点击命令，增加偏移
    :param pcos: 点击控件中心坐标，如（10，20）
    :param x_ofset: x方向偏移区间，[min.max]，默认偏移为0
    :param y_ofset: y方向偏移区间，[min.max]，默认偏移为0
    :param times: 点击次数，默认点击1次
    :param kwargs:
    :return:
    '''
    x_ofset = random.randint(x_ofset[0], x_ofset[1])
    y_ofset = random.randint(y_ofset[0], y_ofset[1])
    G.LOGGING.info(f"点击坐标为（{(pcos[0] + x_ofset, pcos[1] + y_ofset)}）")
    touch((pcos[0] + x_ofset, pcos[1] + y_ofset),times=times,**kwargs)


if __name__ == '__main__':
    # minimize_app("pycham")  # 最小化pycharm
    # sleep(2)
    # # start_menghua(apps=5)
    # pyautogui.screenshot(f'{base_path}/picture/img04.png')  # 截图
    # # devices(mv_id=0)
    # apps = [2, 3, 4, 5, 7]
    # t = get_hwnd_from_title(apps)
    # print(t)
    connect_device(f"Android:///bb6cc8c7")
